﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using QLHD.Models;
using System.Globalization;
using System.Web.Services;
using System.Xml;
using System.Runtime.Serialization;
using QLHD.Utilities;
using System.Threading;
using System.Linq.Expressions;

namespace QLHD.WS
{
    public partial class hdservice : System.Web.UI.Page
    {
        static QLHD2013Entities db = new QLHD2013Entities();
        protected void Page_Load(object sender, EventArgs e)
        {

        }


        [WebMethod(enableSession: true)]
        public static object GetListContract(Search obj)
        {
            QLHD2013Entities db = new QLHD2013Entities();
            List<hd> lst = new List<hd>();
            string keyword = obj.Keyword;
            string sohd = obj.SoHD;
            string doiTac = obj.DoiTac;
            string fromd = obj.FromDT;
            string tod = obj.ToDT;
            int page = int.Parse(obj.page);
            int pagesize = int.Parse(obj.pageSize);
            int skip = int.Parse(obj.skip);
            int take = int.Parse(obj.take);
            int parentid = 0;
            int contracttype = 0;
            int departmentid = 0;

            if (!string.IsNullOrEmpty(obj.DepartmentID))
                departmentid = int.Parse(obj.DepartmentID);
            if (!string.IsNullOrEmpty(obj.ParentID))
            {
                parentid = int.Parse(obj.ParentID);
            }
            if (!string.IsNullOrEmpty(obj.ContractType))
            {
                contracttype = int.Parse(obj.ContractType);
                if (contracttype <= 0)
                    contracttype = 0;
            }
            List<HopDong> lsthopdong;
            int total = 0;
            if (string.IsNullOrEmpty(keyword))
                keyword = Constants.SPLIT_CHAR;
            else
                keyword = keyword.ToLower();

            hdservice ut = new hdservice();
            List<int> viewphongbanids = ut.GetViewDepartmentIDs();
            if (parentid > 0)
            {
                lsthopdong = db.HopDongs.Where(q => q.TrangThaiHD == 1 && q.ParentID == parentid && q.TypeID == contracttype).ToList();
                lsthopdong.RemoveAll(q => q.DepartmentID != null && !viewphongbanids.Contains((int)q.DepartmentID));
                total = lsthopdong.Count();
                lsthopdong = lsthopdong.OrderByDescending(q => q.MaHD).Skip((page - 1) * pagesize).Take(pagesize).ToList();
            }
            else
            {
                DateTime fromdate = DateTime.Parse("01/01/1901 00:00:00");
                DateTime todate = DateTime.Parse("09/09/2099 23:59:59");
                var provider = new CultureInfo("vi-VN");
                if (!string.IsNullOrEmpty(fromd))
                    fromdate = Convert.ToDateTime(fromd + " 00:00:00", provider);

                if (!string.IsNullOrEmpty(tod))
                    todate = Convert.ToDateTime(tod + " 23:59:59", provider);

                lsthopdong = db.HopDongs.Where(q =>
                    q.TrangThaiHD == 1
                    && (q.ParentID == null || q.ParentID == 0)
                    && (q.SearchContent.Contents.Contains(keyword))
                    //&& ()
                    ).ToList();
                DateTime today = DateTime.Today;
                today = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0);
                if (obj.LoadType.ToLower() == "notify")
                {
                    lsthopdong = lsthopdong.Where(q => q.CanhBaoTruoc != null && q.ThoiGianNopBaoCao <= today.AddDays((int)q.CanhBaoTruoc) && q.ThoiGianNopBaoCao >= today).ToList();
                }
                if (departmentid > 0)
                {
                    lsthopdong = lsthopdong.Where(q => q.DepartmentID == departmentid).ToList();
                }
                lsthopdong.RemoveAll(q => q.DepartmentID != null && !viewphongbanids.Contains((int)q.DepartmentID));

                lsthopdong = lsthopdong.Where(q => q.NgayTaoHD >= fromdate && q.NgayTaoHD <= todate).ToList();
                if (!string.IsNullOrEmpty(doiTac))
                {
                    doiTac = doiTac.Trim().Trim(',').ToLower();
                    lsthopdong = lsthopdong.Where(q => q.DoiTac != null && q.DoiTac.TenDoiTac.ToLower() == doiTac).ToList();
                }

                if (!string.IsNullOrEmpty(sohd))
                {
                    sohd = sohd.Trim().ToLower();
                    lsthopdong = lsthopdong.Where(q => q.SoHD.ToLower() == sohd).ToList();
                }

                total = lsthopdong.Count();
                lsthopdong = lsthopdong.OrderByDescending(q => q.MaHD).Skip((page - 1) * pagesize).Take(pagesize).ToList();
            }

            #region comment out
            //string query = "SELECT * FROM  ( SELECT HopDong.*,DoiTac.TenDoiTac, ROW_NUMBER() OVER(ORDER BY MaHD DESC) AS RowNumber FROM HopDong LEFT JOIN DoiTac ON HopDong.MaDoiTac=DoiTac.MaDoiTac WHERE TrangThaiHD=1 {0}) temp WHERE temp.RowNumber BETWEEN @startRowNumber AND @endRowNumber";
            //string condition = "";
            //if (parentid > 0)
            //{
            //    condition = " AND ParentID=" + parentid;
            //}
            //else
            //{
            //    condition = " AND ParentID IS NULL ";
            //}

            //query = string.Format(query, condition);

            ////check quyen xem hop dong thuoc phong nao
            //SqlParameter startRowNumber = new SqlParameter("startRowNumber", (page - 1) * pagesize);
            //SqlParameter endRowNumber = new SqlParameter("endRowNumber", page * pagesize);

            //lsthopdong = db.ExecuteStoreQuery<HopDong>(query, startRowNumber, endRowNumber);
            //var source = (from item in db.HopDongs.Where(q=>q.TrangThaiHD==1).OrderByDescending(q => q.NgayTaoHD).Skip((page - 1) * pagesize).Take(pagesize).ToList()

            #endregion
            DateTime now = DateTime.Now;
            List<hd> source = new List<hd>();
            int i = 1;
            int num = 1;
            foreach (HopDong item in lsthopdong)
            {
                var _hd = GetHDModel(item, i.ToString());
                _hd.STT = ((page - 1) * pagesize + i).ToString();
                source.Add(_hd);

                if (parentid > 0)
                {
                    source.AddRange(GetChildren(item, contracttype, "", out num));
                }
                else
                {
                    num = 1;
                    source.AddRange(GetChildren(item, 0, i.ToString(), out num));
                    source.AddRange(GetChildren(item, 1, i.ToString(), out num, num + 1));
                }
                i++;
            }


            return new { source, total = total };
        }
        [WebMethod]
        public static void CreateContract(IEnumerable<hd> obj, int ParentID, int ContractType)
        {
            db = new QLHD2013Entities();
            HopDong newhd = new HopDong();
            hdservice ut = new hdservice();
            foreach (hd item in obj)
            {
                if (!string.IsNullOrEmpty(item.DepartmentID) && int.Parse(item.DepartmentID) > 0)
                {
                    if (!ut.IsValidDepartment(int.Parse(item.DepartmentID)))
                        continue;
                    newhd.DepartmentID = int.Parse(item.DepartmentID);
                }
                else
                {
                    newhd.DepartmentID = null;
                }

                //newhd.MaHD = obj.MaHD;
                newhd.TenHD = item.TenHD;
                newhd.SoHD = item.SoHD;
                //if (!string.IsNullOrEmpty(obj.MaDoiTac))
                //    newhd.MaDoiTac = int.Parse(obj.MaDoiTac);
                if (item.GiaTriHD != null)
                    newhd.GiaTriHD = decimal.Parse(item.GiaTriHD);

                if (string.IsNullOrEmpty(item.ThoiGianNopBaoCao))
                {
                    newhd.ThoiGianNopBaoCao = null;
                }
                else
                {
                    newhd.ThoiGianNopBaoCao = Utilities.Utilities.ConvertToDateTime(item.ThoiGianNopBaoCao);
                }
                newhd.TienDoThucHien = item.TienDoThucHien;
                newhd.GhiChu = item.GhiChu;
                newhd.ChuNhiemCongTrinh = item.ChuNhiemCongTrinh;
                newhd.CanhBaoTruoc = !string.IsNullOrEmpty(item.CanhBaoTruoc) ? int.Parse(item.CanhBaoTruoc) : 1;
                if (!string.IsNullOrEmpty(item.NgayThanhLyHD))
                {
                    newhd.NgayThanhLyHD = Utilities.Utilities.ConvertToDateTime(item.NgayThanhLyHD);
                }
                else
                {
                    newhd.NgayThanhLyHD = null;
                }

                if (!string.IsNullOrEmpty(item.GiaTriThanhLyHD))
                {
                    newhd.GiaTriThanhLyHD = decimal.Parse(item.GiaTriThanhLyHD);
                }
                if (!string.IsNullOrEmpty(item.NgayTaoHD))
                {
                    newhd.NgayTaoHD = Utilities.Utilities.ConvertToDateTime(item.NgayTaoHD);
                }
                else
                {
                    newhd.NgayTaoHD = DateTime.Now;
                }
                newhd.TrangThaiHD = 1;
                newhd.LastUpdate = DateTime.Now;

                if (ParentID > 0)
                {
                    newhd.ParentID = ParentID;
                }
                if (ContractType > 0)
                    newhd.TypeID = ContractType;
                else
                {
                    newhd.TypeID = 0;
                }

                string doitac = item.TenDoiTac;
                if (!string.IsNullOrEmpty(doitac))
                {
                    doitac = item.TenDoiTac.Trim().Trim(',');
                    var dtac = db.DoiTacs.Where(q => q.TenDoiTac.ToLower() == doitac.ToLower() && q.TrangThai == true).FirstOrDefault();
                    if (dtac != null)
                    {
                        newhd.MaDoiTac = dtac.MaDoiTac;
                    }
                    else
                    {
                        dtac = DoiTac.CreateDoiTac(0, doitac);
                        dtac.TrangThai = true;
                        newhd.DoiTac = dtac;
                    }
                }

                History his = History.CreateHistory(0, 1, 0, DateTime.Now);
                his.IP = HttpContext.Current.Request.UserHostAddress;
                newhd.Histories.Add(his);
                db.AddToHopDongs(newhd);
                db.SaveChanges();
                if (ParentID > 0)
                {
                    if (newhd.HopDong2.TopParentID > 0)
                    {
                        newhd.TopParentID = newhd.HopDong2.TopParentID;
                    }
                    else
                    {
                        newhd.TopParentID = ParentID;
                    }
                    //them history cho hop dong goc
                    his = History.CreateHistory(0, 1, (int)newhd.TopParentID, DateTime.Now);
                    his.IP = HttpContext.Current.Request.UserHostAddress;
                    db.AddToHistories(his);
                    db.SaveChanges();
                }
                if (newhd.HopDong3 != null)
                {
                    Utilities.Utilities.UpdateSearchContent(newhd.HopDong3, db, false);
                }
                else
                {
                    Utilities.Utilities.UpdateSearchContent(newhd, db, false);
                }
                db.SaveChanges();
            }
        }

        [WebMethod]
        public static void UpdateContract(IEnumerable<hd> obj)
        {
            db = new QLHD2013Entities();
            foreach (hd item in obj)
            {
                int mahd = int.Parse(item.MaHD);
                hdservice ut = new hdservice();
                HopDong newhd = db.HopDongs.Where(q => q.MaHD == mahd).FirstOrDefault();
                if (newhd != null)
                {
                    if (newhd.DepartmentID != null && newhd.DepartmentID > 0 && !ut.IsValidDepartment((int)newhd.DepartmentID))
                        continue;

                    if (!string.IsNullOrEmpty(item.DepartmentID) && int.Parse(item.DepartmentID) > 0)
                    {
                        if (!ut.IsValidDepartment(int.Parse(item.DepartmentID)))
                            continue;
                        newhd.DepartmentID = int.Parse(item.DepartmentID);
                    }
                    else
                    {
                        newhd.DepartmentID = null;
                    }
                    //newhd.MaHD = obj.MaHD;
                    newhd.TenHD = item.TenHD;
                    newhd.SoHD = item.SoHD;
                    //if (!string.IsNullOrEmpty(obj.MaDoiTac))
                    //    newhd.MaDoiTac = int.Parse(obj.MaDoiTac);
                    if (item.GiaTriHD != null)
                        newhd.GiaTriHD = decimal.Parse(item.GiaTriHD);

                    if (string.IsNullOrEmpty(item.ThoiGianNopBaoCao))
                    {
                        newhd.ThoiGianNopBaoCao = null;
                    }
                    else
                    {
                        newhd.ThoiGianNopBaoCao = Utilities.Utilities.ConvertToDateTime(item.ThoiGianNopBaoCao);
                    }
                    newhd.TienDoThucHien = item.TienDoThucHien;
                    newhd.GhiChu = item.GhiChu;
                    newhd.ChuNhiemCongTrinh = item.ChuNhiemCongTrinh;
                    newhd.CanhBaoTruoc = !string.IsNullOrEmpty(item.CanhBaoTruoc) ? int.Parse(item.CanhBaoTruoc) : 1;
                    if (!string.IsNullOrEmpty(item.NgayThanhLyHD))
                    {
                        newhd.NgayThanhLyHD = Utilities.Utilities.ConvertToDateTime(item.NgayThanhLyHD);
                    }
                    else
                    {
                        newhd.NgayThanhLyHD = null;
                    }

                    if (!string.IsNullOrEmpty(item.GiaTriThanhLyHD))
                    {
                        newhd.GiaTriThanhLyHD = decimal.Parse(item.GiaTriThanhLyHD);
                    }
                    //newhd.TrangThaiHD = 1;
                    newhd.LastUpdate = DateTime.Now;

                    if (newhd.ParentID > 0 && newhd.TopParentID == null)//update record loi
                    {
                        if (newhd.HopDong2.TopParentID > 0)
                        {
                            newhd.TopParentID = newhd.HopDong2.TopParentID;
                        }
                        else
                        {
                            newhd.TopParentID = newhd.ParentID;
                        }
                    }

                    if (newhd.TopParentID != null)
                    {
                        var his1 = History.CreateHistory(0, 1, (int)newhd.TopParentID, DateTime.Now);
                        his1.IP = HttpContext.Current.Request.UserHostAddress;
                        db.AddToHistories(his1);

                        //Thread th = new Thread(new ParameterizedThreadStart(UpdateSearchContent));
                        //th.Start(newhd.HopDong3);
                        Utilities.Utilities.UpdateSearchContent(newhd.HopDong3, db);
                    }
                    else
                    {
                        //Thread th = new Thread(new ParameterizedThreadStart(UpdateSearchContent));
                        //th.Start(newhd);
                        Utilities.Utilities.UpdateSearchContent(newhd, db);
                    }



                    if (!string.IsNullOrEmpty(item.NgayTaoHD))
                    {
                        newhd.NgayTaoHD = Utilities.Utilities.ConvertToDateTime(item.NgayTaoHD);
                    }
                    string doitac = item.TenDoiTac;
                    if (!string.IsNullOrEmpty(doitac))
                    {
                        doitac = item.TenDoiTac.Trim().Trim(',');
                        var dtac = db.DoiTacs.Where(q => q.TenDoiTac.ToLower() == doitac.ToLower() && q.TrangThai == true).FirstOrDefault();
                        if (dtac != null && dtac.MaDoiTac != newhd.MaDoiTac)
                        {
                            newhd.MaDoiTac = dtac.MaDoiTac;
                        }
                        else if (dtac == null)
                        {
                            dtac = DoiTac.CreateDoiTac(0, doitac);
                            dtac.TrangThai = true;
                            newhd.DoiTac = dtac;
                        }
                    }

                    History his = History.CreateHistory(0, 1, 0, DateTime.Now);
                    his.IP = HttpContext.Current.Request.UserHostAddress;
                    newhd.Histories.Add(his);
                }
            }
            db.SaveChanges();


        }

        [WebMethod]
        public static void DeleteContract(int MaHD)
        {
            QLHD2013Entities db = new QLHD2013Entities();
            int mahd = MaHD;
            var hd = db.HopDongs.Where(q => q.MaHD == mahd).FirstOrDefault();
            if (hd != null)
            {
                hd.TrangThaiHD = 0;
                db.SaveChanges();
            }
        }

        #region XNKL

        [WebMethod(enableSession: true)]
        public static IEnumerable<dynamic> ListXNKL(Search obj)
        {
            string keyword = obj.Keyword;
            int page = int.Parse(obj.page);
            int pagesize = int.Parse(obj.pageSize);
            int skip = int.Parse(obj.skip);
            int take = int.Parse(obj.take);

            QLHD2013Entities db = new QLHD2013Entities();
            int mahopdong = int.Parse(keyword);
            var lstxnkl = db.XNKLs.Where(q => q.MaHD == mahopdong).OrderByDescending(q => q.NgayXNKL).Skip((page - 1) * pagesize).Take(pagesize).ToList();

            return (from item in lstxnkl
                    select new
                    {
                        NoiDung = item.NoiDung,
                        MaXNKL = item.MaXNKL,
                        GiaTri = item.GiaTri != null ? ((decimal)item.GiaTri).ToString("N", CultureInfo.CreateSpecificCulture("en-US")) : "",
                        SoHoaDon = item.SoHoaDon,
                        NgayXNKL = item.NgayXNKL.ToString("dd/MM/yyyy"),
                        GhiChu = item.GhiChu

                    }).ToList<dynamic>();
        }

        [WebMethod]
        public static void CreateXNKL(IEnumerable<XNKLAjax> obj)
        {
            XNKL newxnkl = new XNKL();
            QLHD2013Entities db = new QLHD2013Entities();
            int mahd = 0;
            foreach (XNKLAjax item in obj)
            {
                newxnkl = new XNKL();
                newxnkl.MaHD = int.Parse(item.MaHD);
                if (!string.IsNullOrEmpty(item.GiaTri))
                    newxnkl.GiaTri = decimal.Parse(item.GiaTri);
                newxnkl.SoHoaDon = item.SoHoaDon;
                if (!string.IsNullOrEmpty(item.NgayXNKL))
                {
                    DateTime dt = Utilities.Utilities.ConvertToDateTime(item.NgayXNKL);
                    newxnkl.NgayXNKL = dt;
                }
                else
                {
                    newxnkl.NgayXNKL = DateTime.Now;
                }
                newxnkl.NoiDung = item.NoiDung;
                newxnkl.GhiChu = item.GhiChu;
                db.AddToXNKLs(newxnkl);
            }
            db.SaveChanges();

            if (newxnkl != null && newxnkl.HopDong != null)
            {
                if (newxnkl.HopDong.TopParentID != null)
                {
                    mahd = (int)newxnkl.HopDong.TopParentID;
                }
                else
                {
                    mahd = newxnkl.HopDong.MaHD;
                }
                History his = History.CreateHistory(0, 1, mahd, DateTime.Now);
                his.IP = HttpContext.Current.Request.UserHostAddress;
                db.AddToHistories(his);
                db.SaveChanges();

                if (newxnkl.HopDong.HopDong3 != null)
                {
                    Utilities.Utilities.UpdateSearchContent(newxnkl.HopDong.HopDong3, db);
                }
                else
                {
                    Utilities.Utilities.UpdateSearchContent(newxnkl.HopDong, db);
                }
            }
        }

        [WebMethod]
        public static void UpdateXNKL(IEnumerable<XNKLAjax> obj)
        {
            QLHD2013Entities db = new QLHD2013Entities();
            int mahd = 0;
            XNKL editxnkl = null;
            foreach (XNKLAjax item in obj)
            {
                int MaXNKL = int.Parse(item.MaXNKL);
                editxnkl = db.XNKLs.Where(q => q.MaXNKL == MaXNKL).FirstOrDefault();
                if (editxnkl != null)
                {
                    if (editxnkl.HopDong.TopParentID != null)
                    {
                        mahd = (int)editxnkl.HopDong.TopParentID;
                    }
                    else
                    {
                        mahd = editxnkl.HopDong.MaHD;
                    }
                    //editxnkl.MaHD = int.Parse(item.MaHD);
                    if (!string.IsNullOrEmpty(item.GiaTri))
                        editxnkl.GiaTri = decimal.Parse(item.GiaTri);
                    editxnkl.SoHoaDon = item.SoHoaDon;
                    if (!string.IsNullOrEmpty(item.NgayXNKL))
                    {
                        DateTime dt = Utilities.Utilities.ConvertToDateTime(item.NgayXNKL);
                        editxnkl.NgayXNKL = dt;
                    }
                    else
                    {
                        editxnkl.NgayXNKL = DateTime.Now;
                    }
                    editxnkl.NoiDung = item.NoiDung;
                    editxnkl.GhiChu = item.GhiChu;
                }
            }
            History his = History.CreateHistory(0, 1, mahd, DateTime.Now);
            his.IP = HttpContext.Current.Request.UserHostAddress;
            db.AddToHistories(his);
            db.SaveChanges();

            if (editxnkl.HopDong.HopDong3 != null)
            {
                Utilities.Utilities.UpdateSearchContent(editxnkl.HopDong.HopDong3, db);
            }
            else
            {
                Utilities.Utilities.UpdateSearchContent(editxnkl.HopDong, db);
            }

        }

        [WebMethod]
        public static void DestroyXNKL(XNKLAjax obj)
        {

        }

        #endregion

        #region KCP

        [WebMethod(enableSession: true)]
        public static object ListKCP(Search obj)
        {
            string keyword = obj.Keyword;
            int page = int.Parse(obj.page);
            int pagesize = int.Parse(obj.pageSize);
            int skip = int.Parse(obj.skip);
            int take = int.Parse(obj.take);

            List<int> viewphongbanids = new hdservice().GetViewDepartmentIDs();

            QLHD2013Entities db = new QLHD2013Entities();

            List<HopDong> lsthopdong = new List<HopDong>();

            int mahopdong = 0;
            //if (!string.IsNullOrEmpty(keyword))
            //    mahopdong = int.Parse(keyword);

            List<KhoanChiPhi> lstxnkl = null;
            if (mahopdong > 0)
            {
                lsthopdong = db.HopDongs.Where(IsContain(viewphongbanids).Compile())
               .Where(q =>
                   q.TrangThaiHD == 1
                   && q.MaHD == mahopdong
                   && (q.ParentID == null || q.ParentID == 0)).ToList();

                //lstxnkl = db.KhoanChiPhis.Where(q => q.MaHD == mahopdong && q.TrangThai == true && q.ParentID == null).OrderByDescending(q => q.Ngay).Skip((page - 1) * pagesize).Take(pagesize).ToList();
            }
            else
            {
                lsthopdong = db.HopDongs.Where(IsContain(viewphongbanids).Compile())
                .Where(q =>
                    q.TrangThaiHD == 1
                    && (q.ParentID == null || q.ParentID == 0)
                    && (q.SearchContent.Contents.Contains(keyword))
                    ).OrderByDescending(q => q.MaHD).ToList();
                //lstxnkl = db.KhoanChiPhis.Where(q => q.ParentID == null && q.TrangThai == true).OrderByDescending(q => q.Ngay).Skip((page - 1) * pagesize).Take(pagesize).ToList();
            }

            int total = lsthopdong.Count();
            List<dynamic> source = new List<dynamic>();
            int num = 1;
            int i = 1;
            foreach (HopDong hd in lsthopdong)
            {
                source.Add(GetKCPModel(hd, ((page - 1) * pagesize + i).ToString()));

                var kcps = hd.KhoanChiPhis.Where(q => q.ParentID == null && q.TrangThai == true).ToList();
                int j = 1;
                foreach (KhoanChiPhi kcp in kcps)
                {
                    var _kcp = GetKCPModel(kcp, ((page - 1) * pagesize + i).ToString() + "." + j.ToString());
                    source.Add(_kcp);

                    num = 1;
                    source.AddRange(GetKCPChildren(kcp, "", out num));

                    j++;
                }

                i++;
            }


            //foreach (var item in lstxnkl)
            //{
            //    var _kcp = GetKCPModel(item, ((page - 1) * pagesize + i).ToString());
            //    source.Add(_kcp);
            //    num = 1;
            //    source.AddRange(GetKCPChildren(item, i.ToString(), out num));
            //    i++;
            //}

            //var source = (from item in lstxnkl
            //              select new
            //              {
            //                  STT = ((page - 1) * pagesize + lstxnkl.IndexOf(item) + 1).ToString(),
            //                  MaKCP = item.MaKCP,
            //                  MaHD = item.MaHD,
            //                  SoKCP = item.SoKCP,
            //                  Noidung = item.NoiDung,
            //                  GiaTri = Utilities.Utilities.GetDecimalValue(item.GiaTri),
            //                  GhiChu = item.GhiChu,

            //                  CPGK_TTTC = Utilities.Utilities.GetDecimalValue(item.CPGK_TTTC),
            //                  CPGK_QuaCTy = Utilities.Utilities.GetDecimalValue(item.CPGK_QuaCTy),
            //                  CPGK_TKCM = Utilities.Utilities.GetDecimalValue(item.CPGK_TKCM),
            //                  CPGK_ThueChuyenGia = Utilities.Utilities.GetDecimalValue(item.CPGK_ThueChuyenGia),
            //                  CPGK_PTMauTN = Utilities.Utilities.GetDecimalValue(item.CPGK_PTMauTN),
            //                  CPGK_PTMauMT = Utilities.Utilities.GetDecimalValue(item.CPGK_PTMauMT),
            //                  CPGK_HoaChat = Utilities.Utilities.GetDecimalValue(item.CPGK_HoaChat),
            //                  CPGK_Luong = Utilities.Utilities.GetDecimalValue(item.CPGK_Luong),
            //                  CPGK_CPK = Utilities.Utilities.GetDecimalValue(item.CPGK_CPK),

            //                  CPTH_TTTC = Utilities.Utilities.GetDecimalValue(item.CPTH_TTTC),
            //                  CPTH_QuaCty = Utilities.Utilities.GetDecimalValue(item.CPTH_QuaCty),
            //                  CPTH_TKCM = Utilities.Utilities.GetDecimalValue(item.CPTH_TKCM),
            //                  CPTH_ThueChuyenGia = Utilities.Utilities.GetDecimalValue(item.CPTH_ThueChuyenGia),
            //                  CPTH_PTMauTN = Utilities.Utilities.GetDecimalValue(item.CPTH_PTMauTN),
            //                  CPTH_PTMauMT = Utilities.Utilities.GetDecimalValue(item.CPTH_PTMauMT),
            //                  CPTH_HoaChat = Utilities.Utilities.GetDecimalValue(item.CPTH_HoaChat),
            //                  CPTH_Luong = Utilities.Utilities.GetDecimalValue(item.CPTH_Luong),
            //                  CPTH_CPK = Utilities.Utilities.GetDecimalValue(item.CPTH_CPK),

            //                  Ngay = item.Ngay != null ? ((DateTime)item.Ngay).ToString("dd/MM/yyyy") : ""

            //              }).ToList<dynamic>();
            return new { source, total = total };
        }

        [WebMethod]
        public bool DeleteKCP(int MaKCP)
        {
            QLHD2013Entities db = new QLHD2013Entities();
            int makcp = MaKCP;
            var hd = db.KhoanChiPhis.Where(q => q.MaKCP == MaKCP).FirstOrDefault();
            if (hd != null)
            {
                db.DeleteObject(hd);
                db.SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        private static List<hd> GetChildren(HopDong root, int contracttype, string firstnumber, out int num, int startnum = 1)
        {
            List<hd> child = new List<hd>();
            num = 0;
            if (root.HopDong1 == null && root.HopDong1.Where(q => q.TrangThaiHD == 1 && q.TypeID == contracttype).Count() == 0)
                return child;
            int i = 0;
            int j = 0;
            foreach (HopDong item in root.HopDong1.Where(q => q.TrangThaiHD == 1 && q.TypeID == contracttype))
            {
                child.Add(GetHDModel(item, firstnumber + "." + (i + startnum)));
                child.AddRange(GetChildren(item, contracttype, firstnumber + "." + (i + 1), out j));
                i++;
            }
            num = i;
            return child;
        }

        //private static List<hd> GetChildren(HopDong root, string firstnumber)
        //{
        //    List<hd> child = new List<hd>();
        //    if (root.HopDong1 == null && root.HopDong1.Where(q => q.TrangThaiHD == 1).Count() == 0)
        //        return child;
        //    int i = 1;
        //    foreach (HopDong item in root.HopDong1.Where(q => q.TrangThaiHD == 1))
        //    {
        //        child.Add(GetHDModel(item, firstnumber + "." + i));
        //        child.AddRange(GetChildren(item, firstnumber + "." + i));
        //        i++;
        //    }
        //    return child;
        //}

        private static hd GetHDModel(HopDong item, string firstnumber)
        {
            return new hd()
                {
                    STT = firstnumber,
                    MaHD = item.MaHD.ToString(),
                    TenHD = item.TenHD,
                    SoHD = item.SoHD,
                    MaDoiTac = item.MaDoiTac != null ? item.MaDoiTac.ToString() : "",
                    TenDoiTac = (item.DoiTac != null) ? item.DoiTac.TenDoiTac : "",
                    GiaTriHD = item.GiaTriHD != null ? ((decimal)item.GiaTriHD).ToString("N", CultureInfo.CreateSpecificCulture("en-US")) : "",
                    ThoiGianNopBaoCao = item.ThoiGianNopBaoCao != null ? ((DateTime)item.ThoiGianNopBaoCao).ToString("dd/MM/yyyy") : "",
                    TienDoThucHien = item.TienDoThucHien,
                    GhiChu = item.GhiChu,
                    ChuNhiemCongTrinh = item.ChuNhiemCongTrinh,
                    NgayThanhLyHD = item.NgayThanhLyHD != null ? ((DateTime)item.NgayThanhLyHD).ToString("dd/MM/yyyy") : "",
                    GiaTriThanhLyHD = item.GiaTriThanhLyHD != null ? ((decimal)item.GiaTriThanhLyHD).ToString("N", CultureInfo.CreateSpecificCulture("en-US")) : "",
                    ParentID = item.ParentID != null ? item.ParentID.ToString() : "",
                    NgayTaoHD = item.NgayTaoHD != null ? ((DateTime)item.NgayTaoHD).ToString("dd/MM/yyyy") : "",
                    DepartmentID = item.DepartmentID != null ? item.DepartmentID.ToString() : "0",
                    CanhBaoTruoc = item.CanhBaoTruoc != null ? item.CanhBaoTruoc.ToString() : ""
                };
        }

        private static List<dynamic> GetKCPChildren(KhoanChiPhi root, string firstnumber, out int num, int startnum = 1)
        {
            List<dynamic> child = new List<dynamic>();
            num = 0;
            if (root.KhoanChiPhi1 == null && root.KhoanChiPhi1.Where(q => q.TrangThai == true).Count() == 0)
                return child;
            int i = 0;
            int j = 0;
            foreach (KhoanChiPhi item in root.KhoanChiPhi1.Where(q => q.TrangThai == true))
            {
                string fn = string.IsNullOrEmpty(firstnumber) ? "" : firstnumber + "." + (i + startnum);
                string fn1 = string.IsNullOrEmpty(firstnumber) ? "" : firstnumber + "." + (i + 1);
                child.Add(GetKCPModel(item, fn));
                child.AddRange(GetKCPChildren(item, fn1, out j));
                i++;
            }
            num = i;
            return child;
        }

        private static dynamic GetKCPModel(KhoanChiPhi item, string firstnumber)
        {
            return new
                           {
                               STT = firstnumber,
                               Noidung = item.NoiDung,
                               SoHD = "",
                               NgayTaoHD = "",
                               GiaTriHD = "",

                               MaKCP = item.MaKCP,
                               MaHD = item.MaHD,
                               SoKCP = item.SoKCP,
                               GiaTri = Utilities.Utilities.GetDecimalValue(item.GiaTri),
                               GhiChu = item.GhiChu,

                               CPGK_TTTC = Utilities.Utilities.GetDecimalValue(item.CPGK_TTTC),
                               CPGK_QuaCTy = Utilities.Utilities.GetDecimalValue(item.CPGK_QuaCTy),
                               CPGK_TKCM = Utilities.Utilities.GetDecimalValue(item.CPGK_TKCM),
                               CPGK_ThueChuyenGia = Utilities.Utilities.GetDecimalValue(item.CPGK_ThueChuyenGia),
                               CPGK_PTMauTN = Utilities.Utilities.GetDecimalValue(item.CPGK_PTMauTN),
                               CPGK_PTMauMT = Utilities.Utilities.GetDecimalValue(item.CPGK_PTMauMT),
                               CPGK_HoaChat = Utilities.Utilities.GetDecimalValue(item.CPGK_HoaChat),
                               CPGK_Luong = Utilities.Utilities.GetDecimalValue(item.CPGK_Luong),
                               CPGK_CPK = Utilities.Utilities.GetDecimalValue(item.CPGK_CPK),

                               CPTH_TTTC = Utilities.Utilities.GetDecimalValue(item.CPTH_TTTC),
                               CPTH_QuaCty = Utilities.Utilities.GetDecimalValue(item.CPTH_QuaCty),
                               CPTH_TKCM = Utilities.Utilities.GetDecimalValue(item.CPTH_TKCM),
                               CPTH_ThueChuyenGia = Utilities.Utilities.GetDecimalValue(item.CPTH_ThueChuyenGia),
                               CPTH_PTMauTN = Utilities.Utilities.GetDecimalValue(item.CPTH_PTMauTN),
                               CPTH_PTMauMT = Utilities.Utilities.GetDecimalValue(item.CPTH_PTMauMT),
                               CPTH_HoaChat = Utilities.Utilities.GetDecimalValue(item.CPTH_HoaChat),
                               CPTH_Luong = Utilities.Utilities.GetDecimalValue(item.CPTH_Luong),
                               CPTH_CPK = Utilities.Utilities.GetDecimalValue(item.CPTH_CPK),

                               Ngay = item.Ngay != null ? ((DateTime)item.Ngay).ToString("dd/MM/yyyy") : ""

                           };
        }

        private static dynamic GetKCPModel(HopDong item, string firstnumber)
        {
            return new
            {
                STT = firstnumber,
                Noidung = item.TenHD,
                SoHD = item.SoHD,
                NgayTaoHD = item.NgayTaoHD,
                GiaTriHD = item.GiaTriHD,

                MaKCP = 0,
                MaHD = item.MaHD,
                SoKCP = "",

                GiaTri = "",
                GhiChu = "",

                CPGK_TTTC = "",
                CPGK_QuaCTy = "",
                CPGK_TKCM = "",
                CPGK_ThueChuyenGia = "",
                CPGK_PTMauTN = "",
                CPGK_PTMauMT = "",
                CPGK_HoaChat = "",
                CPGK_Luong = "",
                CPGK_CPK = "",

                CPTH_TTTC = "",
                CPTH_QuaCty = "",
                CPTH_TKCM = "",
                CPTH_ThueChuyenGia = "",
                CPTH_PTMauTN = "",
                CPTH_PTMauMT = "",
                CPTH_HoaChat = "",
                CPTH_Luong = "",
                CPTH_CPK = "",

                Ngay = ""

            };
        }

        private bool IsValidDepartment(int departmentid)
        {
            var pbs = (List<PhongBan>)Session["phongban"];
            if (Session["phongban"] != null && pbs.Count() > 0)
            {
                return pbs.Where(q => q.ID == departmentid).Count() > 0;
            }
            else
                return false;
        }

        public List<int> GetViewDepartmentIDs()
        {
            var lstpbs = new AuthenticationHelper().GetListPhongban();

            if (lstpbs != null)
            {
                return lstpbs.Select(q => q.ID).ToList();
            }
            else
            {
                return new List<int>();
            }
        }

        private static Expression<Func<HopDong, bool>> IsContain(List<int> lst)
        {
            return p => lst.Where(e => e == p.DepartmentID).Count() > 0;
        }


    }
}